<?php

/**
 * @version			$Id$
 * @create 			2012-04-25 12:04:22 By xjiujiu
 * @package 	 	app.admin
 * @subpackage 	 	action
 * @copyRight 		Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 * HongJuZi Framework
 */
defined('_HEXEC') or die('Restricted access!');

//导入引用文件
HClass::import('config.popo.userpopo, app.admin.action.AdminAction, model.usermodel');

/**
 * 用户列表的动作类 
 * 
 * 主要处理后台管理主页的相关请求动作 
 * 
 * @author 			xjiujiu <xjiujiu@foxmail.com>
 * @package 		app.admin.action
 * @since 			1.0.0
 */
class UserAction extends AdminAction
{

    /**
     * 构造函数 
     * 
     * 初始化类变量 
     * 
     * @access public
     */
    public function __construct() 
    {
        parent::__construct();
        $this->_popo        = new UserPopo();
        $this->_model       = new UserModel($this->_popo);
        if('root' != HSession::getAttribute('actor', 'user')) {
            $this->_model->setMustWhere('is_my', '`id` = ' . HSession::getAttribute('id', 'user'));
        }
    }

    /**
     * 搜索方法 
     * 
     * @access public
     */
    public function search()
    {
        $where  = $this->_combineWhere();
        $this->_search($where);
        $this->_render('user/list');
    }

    protected function _combineWhere() 
    {
        $where  = parent::_combineWhere();
        return $where;
    }

    /**
     * 主页动作 
     * 
     * @access public
     */
    public function index()
    {    
        $where = HRequest::getParameter('type') ?   '`parent_id` = 13' : '1 = 1';
        $this->_search( $where );
        $this->_render('user/list');
    }

    //得到商家名搜索条件
    protected function _getShopWhereByName($name)
    {
        if(!$name) {
            return '1= 1';
        }
        $shop   = HClass::quickLoadModel('shop');
        $record = $shop->getRecordByWhere('`name` = \'' . $name . '\'');
        if(!$record) {
            return ' 1= 2';
        }
        $linkedData     = HClass::quickLoadModel('linkeddata');
        $linkedData->setRelItemModel('user', 'shop');
        $list           = $linkedData->getAllRowsByFields('`rel_id`', '`item_id` = ' . $record['id']);

        HResponse::setAttribute('shop_id', $record['id']);
        HResponse::setAttribute('shopInfo', $record);
        return HSqlHelper::whereInByListMap('id', 'rel_id', $list);
    }

    /**
     * 搜索方法 
     * 
     * @access public
     */
    public function member()
    {
        $actor  = HClass::quickLoadModel('actor');
        $act    = $actor->getRecordByIdentifier('member');
        $where  = '1 = 1';
        if($act){
            $where .= ' AND `parent_id` = ' . $act['id'];
        }
        $this->_popo->modelZhName = '会员';
        HRequest::setParameter('type', $act['id']);
        $this->_search($where);

        $this->_render('user/list');
    }

    /**
     * 全称为CheckUserName即检测当前的用户名 
     * 
     * 当用户名存在时给出错误的提示 
     * 
     * @access public
     */
    public function isunused()
    {
        HVerify::isAjax();
        $userName   = HVerify::isEmptyByVal(HRequest::getParameter('name'), '用户名');
        $id         = HRequest::getParameter('id');
        if(true === $this->_model->isUserNameUsed($userName, $id)) {
            throw new HVerifyException('用户名已经使用！');
        }
        HResponse::json(array('rs' => true, 'message' => '可以使用！'));
    }

    /**
     * 执行模块的添加 
     * 
     * @access public
     */
    public function add()
    {
        if(!HRequest::getParameter('salt')) {
            HRequest::setParameter('salt', rand(10000, 99999));
        }
        $password   = HRequest::getParameter('password');
        if(!$password) {
            HRequest::setParameter('password', rand(10000, 99999));
        }
        $password   = HRequest::getParameter('password', false);
        HVerify::isStrLen($password, '登录密码', 6, 20);
        $this->_formatFieldData();
        $this->_verifyLoginNameAndEmail();
        $this->_add();

        HResponse::json(array(
            'rs' => true, 
            'message' => '新' . $this->_popo->modelZhName . '添加成功！', 'nextUrl' => $this->_getReferenceUrl(1))
        );
    }

    /**
     * 检测用户名或邮箱是否已经使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     * @param $id 用户编号，默认为NULL表示为新加
     * @throws HVerifyException 验证异常
     */
    private function _verifyLoginNameAndEmail($id = null)
    {
        $where  = '(`name` = \'' . HRequest::getParameter('name') . '\'';
        if(HRequest::getParameter('email')) {
            $where  .= ' OR `email` = \'' . HRequest::getParameter('email') . '\')';
        } else {
            $where  .= ')';
        }
        if($id) {
            $where  .= ' AND `id` != ' . $id;
        }
        $record     = $this->_model->getRecordByWhere($where);
        if(!$record) {
            return;
        }
        if($record['name'] == HRequest::getParameter('name')) {
            throw new HVerifyException('用户名已经使用！');
        }

        HVerify::isPhone(HRequest::getParameter('weixin'));
        HVerify::isPhone(HRequest::getParameter('phone'));

        throw new HVerifyException('邮箱已经使用！');
    }

    /**
     * 格式化字段数据
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    private function _formatFieldData($isEdit = false)
    {
        if(HRequest::getParameter('password')) {
            HRequest::setParameter(
                'password',
                $this->_encodePassword(HRequest::getParameter('password'), HRequest::getParameter('salt'))
            );
        }
        HRequest::setParameter('ip', HRequest::getClientIp());
        HRequest::setParameter('login_time', $_SERVER['REQUEST_TIME']);
        HRequest::setParameter('create_time', $_SERVER['REQUEST_TIME']);
    }

    /**
     * 编辑提示动作 
     * 
     * @access public
     */
    public function edit()
    {
        HVerify::isRecordId(HRequest::getParameter('id'), '用户ID');
        if(HRequest::getParameter('password')) {
            HVerify::isStrLen(HRequest::getParameter('password'), '登录密码', 6, 20);
        } else {
            HRequest::deleteParameter('password');
        }
        $this->_formatFieldData(true);
        $this->_verifyLoginNameAndEmail(HRequest::getParameter('id'));
        $record     = $this->_edit();
        if($record['id'] == HSession::getAttribute('id', 'user')) {
            HSession::setAttributeByDomain($record, 'user');
        }
        HResponse::json(array(
            'rs' => true, 
            'message' => '更新成功！', 
            'nextUrl' => $this->_getReferenceUrl(1)
        ));
    }

    /**
     * 删除动作 
     * 
     * @access public
     * @exception HRequestException 请求异常
     */
    public function delete()
    {
        $recordIds  = HRequest::getParameter('id');
        if(!is_array($recordIds)) {
            $recordIds  = array($recordIds);
        }
        if(in_array(HSession::getAttribute('id', 'user'), $recordIds)) {
            throw new HRequestException('删除用户中不能包含自己！');
        }
        $this->_delete($recordIds);
        HResponse::succeed(
            '删除成功！', 
            HResponse::url($this->_popo->modelEnName)
        );
    }

    /**
     * 列表后驱方法
     * @return [type] [description]
     */
    protected function _otherJobsAfterList()
    {
        parent::_otherJobsAfterList();
        HResponse::registerFormatMap('sex', 'name', UserPopo::$sexMap);
    }

    /**
     * 详情后驱方法
     * @return [type] [description]
     */
    protected function _otherJobsAfterInfo()
    {
        parent::_otherJobsAfterInfo();
        HResponse::setAttribute('area_list', UserPopo::$shopVerifyMap);
        HResponse::setAttribute('sex_list', UserPopo::$sexMap);
    }

    /**
     * 异步获取属性规格列表
     * @throws HRequestException
     */
    public function alist()
    {
        HVerify::isAjax();

        $parentId   = HRequest::getParameter('parent_id');
        $perpage    = 50;

        $keyword    = HRequest::getParameter('keyword');
        $where      = '1 = 1';
        if($parentId){
            $where .= ' AND `parent_id` = ' . $parentId;
        }
        if($keyword){
            $where .= ' AND (`name` LIKE \'%' . $keyword . '%\' OR `phone` LIKE \'%' . $keyword . '\')';
        }
        $totalRows  = $this->_model->getTotalRecords($where);
        $totalPages = ceil($totalRows / $perpage);
        $page       = $this->_getPageNumber($totalPages);
        $list       = $this->_model->getListByFields(
            '`id`, `name`, `true_name`, `parent_id`, `phone`',
            $where, $page, $perpage
        );
        $actorMap   = HArray::turnItemValueAsKey($this->_getActorList($list), 'id');
        foreach($list as $key => &$item){
            $item['actor']  = $actorMap[$item['parent_id']] ? $actorMap[$item['parent_id']]['name'] : '未知';
            $item['true_name'] = $item['true_name'] ? $item['true_name'] : '';
            $item['phone'] = $item['phone'] ? $item['phone'] : '';
        }

        HResponse::json(array('rs' => true, 'data' => $list, 'totalPages' => $totalPages));
    }

    /**
     * 获取角色列表
     * @param $list
     * @return Array
     */
    private function _getActorList($list)
    {
        $actor      = HClass::quickLoadModel('actor');
        $actorList  = $actor->getAllRows(HSqlHelper::whereInByListMap('id', 'parent_id', $list));

        return $actorList;
    }

    /**
     * 搜索用户用于支付
     */
    public function asearchforpay()
    {
        HVerify::isAjax();
        $keyword    = HVerify::isEmptyByVal(HRequest::getParameter('query'), '关键词');
        $orderId    = HVerify::isEmptyByVal(HRequest::getParameter('id'), '订单编号');
        $type       = HVerify::isEmptyByVal(HRequest::getParameter('type'), '搜索类别');
        switch($type) {
            case 2:
            $where      = '`phone` = \'' . $keyword . '\'';
            break;
            case 3:
            $where      = '`true_name` = \'' . $keyword . '\'';
            break;
            case 1:
            default:
            $where      = '`name` = \'' . $keyword . '\'';
            break;
        }
        $record     = $this->_model->getRecordByWhere($where);
        if(!$record) {
            throw new HVerifyException('用户没有搜索到，请确认！');
        }
        $avatar = $record['image_path'] ? HResponse::touri($record['image_path']) 
            : HResponse::uri() . 'images/default-avatar.png';
        $data   = array(
            'userInfo' => array(
                'id' => $record['id'],
                'name' => $record['name'],
                'true_name' => $record['true_name'],
                'avatar' => $avatar,
                'lingqian' => $record['total_money'],
                'chongzhi' => $record['total_chongzhi'],
            ),
            'youhuijuan' => $this->_getYouHuiJuanList($record['id'], $orderId)
        );
        HResponse::json(array('rs' => true, 'data' => $data));
    }

    //得到优惠券列表
    private function _getYouHuiJuanList($uid, $orderId)
    {
        $linkeddata     = HClass::quickLoadModel('linkeddata');
        $linkeddata->setRelItemModel('user', 'youhuijuan');
        $list           = $linkeddata->getAllRowsByFields(
            '`id`, `item_id`',
            '`rel_id` = ' . $uid
            . ' AND `extend` = 1'
        );
        if(!$list) {
            return null;
        }
        $youHuiJuan     = HClass::quickLoadModel('youhuijuan');
        $where          = HSqlHelper::whereInByListMap('id', 'item_id', $list);
        $orderGoods     = HClass::quickLoadModel('ordergoods');
        $amount         = $orderGoods->getSum('`price` * `number`', '`parent_id` = ' . $orderId);
        $where          .= ' AND `status` = 2 '
            . ' AND `end_time` > ' . time()
            . ' AND `min_money` <= ' . $amount;
        $yhjList        = $youHuiJuan->getAllRowsByFields('`id`, `min_money`, `sub_money`, `name`', $where);
        $map            = HArray::turnItemValueAsKey($yhjList, 'id');
        $doneList       = array();
        foreach($list as &$item) {
            if(!isset($map[$item['item_id']])) {
                continue;
            }
            $info       = $map[$item['item_id']];
            $item['name']       = $info['name'];
            $item['sub_money']  = $info['sub_money'];
            $item['min_money']  = $info['min_money'];
            $doneList[]         = $item;
        }

        return $doneList;
    }

    /**
     * 新加boss
     * 
     * @return void
     */
    public function anewboss()
    {
        HVerify::isAjax();
        $name       = HVerify::isEmptyByVal(HRequest::getParameter('name'), '登陆账号');
        $password   = HVerify::isEmptyByVal(HRequest::getParameter('password'), '密码');
        $pwdSure    = HVerify::isEmptyByVal(HRequest::getParameter('sure_pwd'), '确认密码');
        $trueName   = HRequest::getParameter('true_name');
        $phone      = HRequest::getParameter('phone');
        HVerify::isStrLen($password, '登录密码', 6, 20);
        if($password != $pwdSure) {
            throw new HVerifyException('两次密码不一致，请确认！');
        }
        if(!HRequest::getParameter('salt')) {
            HRequest::setParameter('salt', rand(10000, 99999));
        }
        $this->_formatFieldData();
        $this->_verifyLoginNameAndEmail();
        //设置成商家超级管理员
        $actor      = HClass::quickLoadModel('actor');
        $shopAdmin  = $actor->getRecordByIdentifier('shopboss');
        HRequest::setParameter('parent_id', $shopAdmin['id']);
        $id     = $this->_add();

        HResponse::json(array('rs' => true, 'data' => array('id' => $id, 'name' => $name)));
    }

}

?>
